package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class BaiduServiceApiImpl implements BaiduServiceApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Boolean updateOrSave(Long userId, String longitude, String latitude, String address) {
        try {
            //查询用户位置是否存在
            Query query = new Query();
            query.addCriteria(Criteria.where("userId").is(userId));
            UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
            //不存在保存
            if (userLocation == null) {
                userLocation = new UserLocation();
                userLocation.setUserId(userId);
                userLocation.setCreated(System.currentTimeMillis());
                userLocation.setUpdated(System.currentTimeMillis());
                userLocation.setLastUpdated(userLocation.getUpdated());
                userLocation.setAddress(address);
                GeoJsonPoint geoJsonPoint = new GeoJsonPoint(
                        Convert.toDouble(longitude),
                        Convert.toDouble(latitude)
                );
                userLocation.setLocation(geoJsonPoint);
                mongoTemplate.save(userLocation);
            } else {
                //存在，更新
                Update update = new Update();
                GeoJsonPoint geoJsonPoint = new GeoJsonPoint(
                        Convert.toDouble(longitude),
                        Convert.toDouble(latitude)
                );
                update.set("location", geoJsonPoint);
                update.set("updated", System.currentTimeMillis());
                update.set("lastUpdated", userLocation.getUpdated());
                update.set("address", address);
                mongoTemplate.updateFirst(query, update, UserLocation.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<UserLocation> getNearUser(Long userId, String distance) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
        if (location == null) {
            return null;
        }

        //获取圆心
        GeoJsonPoint point = location.getLocation();
        //绘制半径
        Distance distance1 = new Distance(Convert.toDouble(distance)/1000, Metrics.KILOMETERS);
        //绘制圆
        Circle circle = new Circle(point, distance1);
        //构建查询条件
        Query query1 = new Query();
        query.addCriteria(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocations = mongoTemplate.find(query1, UserLocation.class);

        return userLocations;
    }


    public List<Long> queryNearUser(Long userId, Double metre) {

        //1、根据用户id，查询用户的位置信息
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
        if(location == null) {
            return null;
        }

        //2、已当前用户位置绘制原点
        GeoJsonPoint point = location.getLocation();

        //3、绘制半径
        Distance distance = new Distance(metre / 1000, Metrics.KILOMETERS);

        //4、绘制圆形
        Circle circle = new Circle(point, distance);

        //5、查询
        Query locationQuery = Query.query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> list = mongoTemplate.find(locationQuery, UserLocation.class);

        // 从List<UserLocation>集合中获取userId字段的值进行返回
        return CollUtil.getFieldValues(list,"userId",Long.class);

    }
}
